import Vue from "vue";
import VueI18n from "vue-i18n";
import { getLanguage } from "./settings/lang";
import { CURRENT_BASE_URL, urlCombine } from "./utilities";

Vue.use(VueI18n);

const messages = {};

// 创建 Vue 语言对象集合
const i18n = new VueI18n({
  locale: getLanguage(),
  fallbackLocale: "zh-CN",
  messages,
  silentTranslationWarn: true, // 防止输出一些警告到控制台
});

export default i18n;

/**
 *
 * @param url 加载的脚本地址
 * @param checkLoad 检测脚本是否加载过的判断
 * @returns
 */
function loadRemoteJs(url: string, checkLoad?: () => boolean) {
  if (checkLoad && checkLoad()) {
    return Promise.resolve(void 0);
  }
  return new Promise(resolve => {
    const scriptEl = document.createElement("script");
    scriptEl.defer = true;
    scriptEl.async = true;
    scriptEl.src = url;
    scriptEl.type = "application/javascript";
    scriptEl.crossOrigin = "anonymous";
    scriptEl.onload = () => {
      resolve(void 0);
      document.head.removeChild(scriptEl);
    };
    document.head.appendChild(scriptEl);
  });
}

export async function loadLanguage(lang: string) {
  if (!messages[lang]) {
    //#region 加载远程Element 语言资源包
    // let langId = lang;
    // if (lang.indexOf("-") >= 0) {
    //   const [langBase, langLocation] = lang.split("-");
    //   langId = langBase.toLocaleLowerCase() + langLocation.toLocaleUpperCase();
    // }
    // const { ELEMENT } = window as any;
    // if (!ELEMENT.lang || !ELEMENT.lang[langId]) {
    //   await loadRemoteJs(`https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-y/element-ui/2.15.7/locale/${lang}.min.js`);
    // }
    // const langElement = ELEMENT.lang[langId] || {};
    const { default: langElement } = await import(`element-ui/lib/locale/lang/${lang}`).catch(() => {});
    //#endregion

    //#region 加载本语言资源包，从 public/lang 下设置
    const localUrl = urlCombine(CURRENT_BASE_URL, `lang/${lang}.json`);
    const resLangLocal = await fetch(localUrl.href);
    let langLocal = {};
    if (resLangLocal.status === 200) {
      langLocal = await resLangLocal.json();
    }
    //#endregion
    i18n.setLocaleMessage(lang, {
      ...langLocal,
      ...langElement,
    });
  }
  i18n.locale = lang;
}
